package com.cfh.spring;

import javax.servlet.ServletContextEvent;

import org.apache.log4j.Logger;
import org.springframework.web.context.ContextLoaderListener;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

public class MyContextLoaderListener extends ContextLoaderListener {
	private static final Logger logger = Logger.getLogger(MyContextLoaderListener.class);

	public static WebApplicationContext webApplicationContext = null;

	@Override
	public void contextInitialized(ServletContextEvent event) {
		logger.debug("MyContextLoaderListener contextInitialized start");
		super.contextInitialized(event);
		try {
			synchronized (MyContextLoaderListener.class) {
				webApplicationContext = WebApplicationContextUtils.getRequiredWebApplicationContext(event.getServletContext());
			}
		} catch (Exception e) {
			logger.error("MyContextLoaderListener contextInitialized failed!", e);
		}

		logger.debug("MyContextLoaderListener contextInitialized end");
	}

	@Override
	public void contextDestroyed(ServletContextEvent event) {
		logger.debug("MyContextLoaderListener contextDestroyed start");
		super.contextDestroyed(event);
		webApplicationContext = null;
		logger.debug("MyContextLoaderListener contextDestroyed end");
	}

	public static WebApplicationContext getWebApplicationContext() {
		if (webApplicationContext == null) {
			logger.warn("getWebApplicationContext is null");
		}
		return webApplicationContext;
	}

}
